<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" inline>
      <el-form-item v-hasRole="['admin']" :label="$t('Department')" prop="deptId">
        <department-select v-model="queryParams.deptId" style="width: 200px" />
      </el-form-item>
      <el-form-item :label="$t('Name')" prop="name">
        <el-input v-model="queryParams.name" clearable />
      </el-form-item>
      <el-form-item :label="$t('Code')" prop="code">
        <el-input v-model="queryParams.code" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          {{ $t("Search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("Reset")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['device:card:add']">{{ $t("Add") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['device:card:export']">{{ $t("Export") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <import-dialog ref="importDialog" @success="refresh">
          <el-button type="warning" plain icon="el-icon-upload" size="mini" @click="handleImport"
            v-hasPermi="['device:card:import']">{{ $t("Import") }}
          </el-button>
        </import-dialog>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="queryPage"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="45" align="center" /> -->
      <el-table-column label="#" type="index" width="45" align="right">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('Id')" align="center" prop="id" width="60" /> -->
      <el-table-column :label="$t('Avatar')" type="index" width="100" align="center">
        <template slot-scope="scope">
          <img class="row-user-avatar" :src="avatar(scope.row)" @click="handleAvatar(scope.row)">
        </template>
      </el-table-column>
      <el-table-column :label="$t('AliasName')" align="left" prop="name" min-width="150" />
      <el-table-column :label="$t('card.Code')" align="left" prop="code" min-width="120" />
      <el-table-column :label="$t('Username')" align="left" prop="username" width="150" />
      <el-table-column :label="$t('Password')" align="left" prop="password" width="150" />
      <el-table-column :label="$t('Operate')" align="left" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['device:card:edit']" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" :title="$t('Modify')"></el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['device:card:delete']" :title="$t('Delete')"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="queryPage" />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="formVisible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="120px">
        <el-form-item :label="$t('Department')" prop="deptId">
          <department-select v-model="form.deptId" :placeholder="$t('device.InsertDepartment')" />
        </el-form-item>
        <el-form-item :label="$t('AliasName')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('InsertAliasName')" />
        </el-form-item>
        <el-form-item :label="$t('card.Code')" prop="code">
          <el-input v-model="form.code" :placeholder="$t('card.InsertCode')" :readonly="form.id !== null" />
        </el-form-item>
        <el-form-item :label="$t('Username')" prop="username">
          <el-input v-model="form.username" :placeholder="$t('card.NoCardUsername')" />
        </el-form-item>
        <el-form-item :label="$t('Password')" prop="password">
          <el-input v-model="form.password" :placeholder="$t('card.NoCardPassword')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="formSubmit">{{ $t("OK") }}</el-button>
        <el-button @click="formCancel">{{ $t("Cancel") }}</el-button>
      </div>
    </el-dialog>
    <avatar-editor-dialog ref="avatarDialog" />
  </div>
</template>

<script>
  import DataEntity from '@/components/DataEntity/DataEntity'
  import deviceCardAPI from "@/api/device/card";
  import DepartmentSelect from "@/views/system/components/DepartmentSelect.vue";
  import AvatarEditorDialog from '@/components/Avatar/AvatarEditorDialog.vue';
  import ImportDialog from '@/views/device/card/ImportDialog.vue';
  import settings from '@/settings'


  export default {
    name: "Device",
    mixins: [DataEntity],
    components: {
      DepartmentSelect,
      AvatarEditorDialog,
      ImportDialog
    },
    data() {
      return {
        currentAPI: deviceCardAPI,
        currentBaseURL: '/device/card',
        currentCode: 'device-card',
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        defaultForm: {
          id: null,
          name: null,
          code: null,
          username: null,
          password: null
        },
        rules: {
          name: [{
            max: 20,
            message: this.$t('MaxLengthIs' [20])
          }],
          username: [{
            max: 20,
            message: this.$t('MaxLengthIs' [20])
          }],
          password: [{
            max: 45,
            message: this.$t('MaxLengthIs' [45])
          }],
          code: [{
            required: true,
            message: this.$t("card.CodeNotNull"),
            trigger: "blur",
          }, {
            max: 25,
            message: this.$t('MaxLengthIs' [25])
          }]
        }
      };
    },
    methods: {
      avatar(item) {
        return item.avatar ? `${settings.baseUrl}${item.avatar}` : require(`@/assets/images/none.png`)
      },
      handleImport() {
        this.$refs['importDialog'].show()
      },
      showBound(row) {
        const vm = this
        this.$prompt(this.$t('card.InsertUsername'), this.$t('card.CreateUser'), {
          inputPattern: /^\S{6,30}$/,
          inputErrorMessage: this.$t('card.UsernameError', [6, 30])
        }).then(({
          value
        }) => {
          deviceCardAPI.createUser({
            ...row,
            username: value
          }).then(() => {
            vm.$message({
              type: 'success',
              message: vm.$t('OperateSuccess')
            })
            row.username = value
            vm.queryPage()
          })
        })
      },
      handleAvatar(row) {
        this.form = Object.assign({}, row)
        this.$refs['avatarDialog'].show(row.avatar, this.saveAvatar)
      },
      saveAvatar(data) {
        const vm = this
        let formData = new FormData();
        formData.append("file", data);
        formData.append("id", this.form.id);
        deviceCardAPI.uploadAvatar(formData).then((res) => {
          vm.$modal.msgSuccess(vm.$t("ModifySuccessful"));
          vm.$refs['avatarDialog'].close();
        });
      },
      handleLink(row) {
        if (row.username) {
          const vm = this
          this.$confirm(this.$t('card.UserBoundOrChangeUser'), this.$t('Tips'), {
            confirmButtonText: this.$t('Change')
          }).then(() => {
            vm.showBound(row)
          })
          return
        }
        this.showBound(row)
      }
    }
  };

</script>
